<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>飞机大战</title>
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet" href="layui-v2.7.6/layui/css/layui.css">
    <script src="js/jquery-3.7.1.js"></script>
    <script src="js/jquery-ui.min.js"></script>

</head>

<body class="box">
    <p id="fraction">分数:</p>
    <!-- 友机 -->
    <div id="hero"></div>

    <audio id="game_music" src="./mp3/game_music.mp3" loop></audio>
    <audio id="bullet" src="./mp3/bullet.mp3" loop></audio>
    <audio id="enemy1_down" src="./mp3/enemy1_down.mp3"></audio>
    <audio id="enemy2_down" src="./mp3/enemy2_down.mp3"></audio>
    <audio id="enemy3_down" src="./mp3/enemy3_down.mp3"></audio>

    <script src="layui-v2.7.6/layui/layui.js"></script>
    <script>
        let begin_index
        let over_index
        let singular_index
        let dbl_index
        let dbl_index_f = false
        let fraction = 0
        let difficult_leve
        let begin_btn = $('#begin')[0]
        //所有的定时器
        let timer_in = []
        //所有的方法
        //生成敌机
        function generateEnemy() {
            let div = document.createElement('div')
            let r_size = Math.floor(Math.random() * 100 + 1)
            let r_location = Math.floor(Math.random() * 100)
            $(div).css({ 'position': 'absolute', 'left': `${r_location}%`, 'top': '0' })
            if (r_size <= 40) {
                $(div).css({ 'background': "url(images/enemy1.png)", 'width': '40px', 'height': '40px' }).attr({ 'id': 'xsEnemy', 'data-bloodBar': 5 })
            } else if (r_size > 40 && r_size <= 60) {
                $(div).css({ 'background': "url(images/enemy2.png)", 'width': '48px', 'height': '65px' }).attr({ 'id': 'mdEnemy', 'data-bloodBar': 10 })
            } else if (r_size > 60 && r_size <= 80) {
                $(div).css({ 'background': "url(images/enemy3.png)", 'width': '100px', 'height': '164px' }).attr({ 'id': 'lgEnemy', 'data-bloodBar': 15 })
            } else if (r_size > 80 && r_size <= 90) {
                $(div).css({ 'background': "url(images/prop.png) 38px 0", 'width': '40px', 'height': '70px' }).attr({ 'id': 'dblBullet' })
            } else {
                $(div).css({ 'background': "url(images/prop.png) 0 0", 'width': '40px', 'height': '68px' }).attr({ 'id': 'clearScreen' })
            }

            document.body.appendChild(div)
            return div
        }
        //随机速度
        function speed(obj) {
            let r_speed = Math.floor(Math.random() * 10 + 1)
            let top = parseInt(obj.style.top);
            setInterval(() => {
                top += 2;
                obj.style.top = `${top}px`;
                //销毁对象
                if (top > document.body.clientHeight) {
                    $(obj).remove()
                }
            }, r_speed);
        }
        //开始
        function begin() {
            begin_index = layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                area: ['420px', '240px'],
                content: `<div class="center-content">
                       <h1>飞机大战</h1>
                       <div class="flex-box">
                       <button class="layui-btn layui-btn-primary layui-border-green" id="begin" style="display:none">开始游戏</button>
                       <button class="layui-btn layui-btn-primary layui-border-green " onclick = difficulty() >开始游戏</button>
                       </div>
            </div>`
            });
            $('#begin').click(function () {
                layer.close(begin_index);
                //分数
                $('#game_music')[0].play()
                $('#bullet')[0].play()
                $('#fraction').html(`分数：${fraction}`)
                $(this).remove()
                //生成子弹
                clearInterval(dbl_index)
                singular_index = setInterval(function () {
                    let bullet = generateBullet()
                    bulletSpeed(bullet)
                }, 80)
                timer_in.push(singular_index)
                pengzhuang()
            })
        }
        //毁灭动画函数
        function destruction(div, url, img_max_width) {
            let width_div = parseInt($(div).css('width'))
            let sum_width = 0
            let des_index = setInterval(() => {
                $(div).css({ 'background': `url(${url}) ${sum_width}px 0px` })
                if (img_max_width > 1000) {
                    sum_width += width_div * 3
                } else {
                    sum_width += width_div
                }
                if (sum_width > img_max_width) {
                    clearInterval(des_index)
                    $(div).remove()
                }
            }, 15);
        }
        //生成子弹
        function generateBullet(num = 1) {
            let div = document.createElement('div')

            switch (num) {
                case 1:
                    $(div).css({ 'background': `url(images/bullet${num}.png)`, 'width': '6px', 'height': '14px' })
                    $(div).css({ 'position': 'absolute', 'left': `${($('#hero')[0].offsetLeft + $('#hero')[0].offsetWidth / 2) - 3}px`, 'top': `${$('#hero')[0].offsetTop}px` }).attr({ 'class': 'bullet' })
                    break;
                case 2:
                    $(div).css({ 'position': 'absolute', 'left': `${($('#hero')[0].offsetLeft + $('#hero')[0].offsetWidth / 2) - 24}px`, 'top': `${$('#hero')[0].offsetTop}px` }).attr({ 'class': 'bullet' })
                    $(div).css({ 'background': `url(images/bullet${num}.png)`, 'width': '48px', 'height': '14px' })
                    break;
            }
            //判断是哪一种子弹
            document.body.appendChild(div)
            return div
        }
        //子弹速度
        function bulletSpeed(obj) {
            let top = parseInt(obj.style.top) || 0;
            setInterval(() => {
                top -= 10;
                obj.style.top = `${top}px`;
                //销毁对象
                if (top < 0) {
                    $(obj).remove()
                }
            }, 1);
        }
        //碰撞检测函数
        function getOverlapArea(div1Rect, div2Rect) {
            const overlapWidth = Math.min(div1Rect.left + div1Rect.width, div2Rect.left + div2Rect.width) - Math.max(div1Rect.left, div2Rect.left);
            const overlapHeight = Math.min(div1Rect.top + div1Rect.height, div2Rect.top + div2Rect.height) - Math.max(div1Rect.top, div2Rect.top);
            return overlapWidth > 0 && overlapHeight > 0 ? overlapWidth * overlapHeight : 0;
        }
        function checkCollision(div1, div2) {
            if (div1 && div2) {
                const div1Rect = div1.getBoundingClientRect();
                const div2Rect = div2.getBoundingClientRect();
                return getOverlapArea(div1Rect, div2Rect) > 0;
            }
            return false;
        }
        //清屏物资函数
        function clear(obj) {
            $(obj).remove()
            let xs = document.querySelectorAll('#xsEnemy');
            let md = document.querySelectorAll('#mdEnemy');
            let lg = document.querySelectorAll('#lgEnemy');
            for (let i = 0; i < xs.length; i++) {
                destruction(xs[i], 'images/enemy1.png', 1)
                fraction = fraction + 500
                $('#fraction').html(`分数：${fraction}`)
            }
            for (let i = 0; i < md.length; i++) {
                destruction(md[i], 'images/enemy2.png', 1)
                fraction = fraction + 1000
                $('#fraction').html(`分数：${fraction}`)
            }
            for (let i = 0; i < lg.length; i++) {
                destruction(lg[i], 'images/enemy3.png', 1)
                fraction = fraction + 1500
                $('#fraction').html(`分数：${fraction}`)
            }

        }
        //碰撞检测
        function pengzhuang() {
            timer_in.push(setInterval(() => {
                //友机碰撞敌机
                let herofly = document.querySelector('#hero');
                let xs = document.querySelectorAll('#xsEnemy');
                let md = document.querySelectorAll('#mdEnemy');
                let lg = document.querySelectorAll('#lgEnemy');
                let bullet = document.querySelectorAll('.bullet')


                //dblBullet是双弹夹资源
                let dblBullet = document.querySelectorAll('#dblBullet')
                let die = false
                //子弹类型
                for (let i = 0; i < dblBullet.length; i++) {
                    if (checkCollision(herofly, dblBullet[i]) && !dbl_index_f) {
                        $(dblBullet[i]).remove()
                        clearInterval(singular_index)
                        //吃到了资源
                        dbl_index_f = true
                        dbl_index = setInterval(function () {
                            let bullet = generateBullet(2)
                            bulletSpeed(bullet)
                        }, 80)
                        timer_in.push(dbl_index)
                        setTimeout(function () {
                            dbl_index_f = false
                            clearInterval(dbl_index)
                            //开启原先的子弹
                            singular_index = setInterval(function () {
                                let bullet = generateBullet()
                                bulletSpeed(bullet)
                            }, 80)
                            timer_in.push(singular_index)
                        }, 3000)
                        
                    }
                }

                //敌机类型判断碰撞
                for (let i = 0; i < xs.length; i++) {
                    // if (checkCollision(herofly, xs[i])) {
                    //     //弹出游戏结束
                    //     //页面层
                    //     over()
                    // }
                    //子弹碰撞敌机
                    for (let j = 0; j < bullet.length; j++) {
                        if (checkCollision(bullet[j], xs[i])) {
                            //弹出游戏结束
                            //让敌机的data-bloodBar减少
                            if (!dbl_index_f) {
                                $(xs[i]).attr('data-bloodBar', $(xs[i]).attr('data-bloodBar') - 1)
                            } else {
                                $(xs[i]).attr('data-bloodBar', $(xs[i]).attr('data-bloodBar') - 2)
                            }
                            let blloodBar = $(xs[i]).attr('data-bloodBar')
                            if ($(xs[i]).attr('data-bloodBar') <= 0) {
                                destruction(xs[i], 'images/enemy1.png', 190)
                                $('#enemy1_down')[0].play()
                                fraction = fraction + 500
                                $('#fraction').html(`分数：${fraction}`)
                            }
                            //销毁子弹
                            $(bullet[j]).remove()
                        }
                    }
                }
                for (let i = 0; i < md.length; i++) {
                    // if (checkCollision(herofly, md[i])) {
                    //     //弹出游戏结束
                    //     //页面层
                    //     //弹出游戏结束
                    //     //页面层
                    //     over()
                    // }
                    //子弹碰撞敌机
                    for (let j = 0; j < bullet.length; j++) {
                        if (checkCollision(bullet[j], md[i])) {

                            //让敌机的data-bloodBar减少
                            if (!dbl_index_f) {
                                $(md[i]).attr('data-bloodBar', $(md[i]).attr('data-bloodBar') - 1)
                            } else {
                                $(md[i]).attr('data-bloodBar', $(md[i]).attr('data-bloodBar') - 2)
                            }
                            let blloodBar = $(md[i]).attr('data-bloodBar')
                            if ($(md[i]).attr('data-bloodBar') <= 0) {
                                destruction(md[i], 'images/enemy2.png', 276)
                                $('#enemy2_down')[0].play()
                                fraction = fraction + 1000
                                $('#fraction').html(`分数：${fraction}`)
                            }
                            //销毁子弹
                            $(bullet[j]).remove()
                        }
                    }
                }
                for (let i = 0; i < lg.length; i++) {
                    /*if (checkCollision(herofly, lg[i])) {
                        //弹出游戏结束
                        //页面
                        over()


                    }*/
                    //子弹碰撞敌机
                    for (let j = 0; j < bullet.length; j++) {
                        if (checkCollision(bullet[j], lg[i])) {

                            //让敌机的data-bloodBar减少
                            if (!dbl_index_f) {
                                $(lg[i]).attr('data-bloodBar', $(lg[i]).attr('data-bloodBar') - 1)
                            } else {
                                $(lg[i]).attr('data-bloodBar', $(lg[i]).attr('data-bloodBar') - 2)
                            }
                            let blloodBar = $(xs[i]).attr('data-bloodBar')
                            if ($(lg[i]).attr('data-bloodBar') <= 0) {
                                destruction(lg[i], 'images/enemy3.png', 1100)
                                $('#enemy3_down')[0].play()
                                fraction = fraction + 1500
                                $('#fraction').html(`分数：${fraction}`)
                            }
                            //销毁子弹
                            $(bullet[j]).remove()
                        }
                    }
                }


                //清屏物资
                let clearScreen = document.querySelectorAll('#clearScreen')
                for (let i = 0; i < clearScreen.length; i++) {
                    if (checkCollision(herofly, clearScreen[i])) {
                        //吃到了清屏
                        clear(clearScreen[i])
                    }
                }

            }, 10))
        }
        //难度选择
        function difficulty() {

            let difficulty_index = layer.open({
                type: 1,
                area: ['420px', '240px'],
                content: `<div class="center-content">
                       <h1>飞机大战</h1>
                       <div class="flex-box">
                       <button class="layui-btn layui-btn-primary layui-border-green" id="easy">简单</button>
                       <button class="layui-btn layui-btn-primary layui-border-green" id="general">一般</button>
                       <button class="layui-btn layui-btn-primary layui-border-green" id="hard">困难</button>
                       </div>
            </div>`
            });

            $('#easy').click(function () {
                layer.close(difficulty_index)
                $('#begin').click()
                difficult_leve = 900
                enemy_create(900)
            })
            $('#general').click(function () {
                layer.close(difficulty_index)
                $('#begin').click()
                difficult_leve = 600
                enemy_create(600)
            })
            $('#hard').click(function () {
                layer.close(difficulty_index)
                $('#begin').click()
                difficult_leve = 300
                enemy_create(300)
            })
        }
        function enemy_create(r = 300) {
            timer_in.push(setInterval(function () {
                if (document.querySelectorAll('body div').length < 60) {
                    let enemy = generateEnemy()
                    speed(enemy)
                }
            }, r))
        }
        //结束
        function over() {
            let herofly = document.querySelector('#hero');
            //关闭所有的定时器
            console.log(timer_in);
            for (let z = 0; z < timer_in.length; z++) {
                clearInterval(timer_in[z]);
            }
            timer_in = []
            begin_index = layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                area: ['420px', '240px'],
                content: `<div class="center-content">
                       <h1>飞机大战</h1>
                       <div class="flex-box">
                        <p>您的分数为${fraction}</p>
                       <button class="layui-btn layui-btn-primary layui-border-green" id="begin" style="display:none">充新开始</button>
                       <button class="layui-btn layui-btn-primary layui-border-green " onclick = difficulty() >重新开始</button>
                       </div>
            </div>`
            });
            $('#begin').click(function () {
                layer.close(begin_index);
                //分数
                $('#game_music')[0].play()
                $('#bullet')[0].play()
                $('#fraction').html(`分数：${fraction = 0}`)
                $('#hero').css({ 'left': '48%', 'top': '80%' })

                $(this).remove()

                //生成子弹
                clearInterval(dbl_index)
                singular_index = setInterval(function () {
                    let bullet = generateBullet()
                    bulletSpeed(bullet)
                }, 80)
                timer_in.push(singular_index)
                pengzhuang()
            })

            //清屏
            let clearScreen = document.querySelectorAll('#clearScreen')
            for (let i = 0; i < clearScreen.length; i++) {
                clear(clearScreen[i])

            }

        }


        //图片向下移动
        $(function () {
            let s = 0
            let body = document.body
            setInterval(function () {
                $(body).css('background', `url(images/background.png) 0px ${s++}px `)
            }, 30)
        })
        begin()
        //电脑上的点击事件
        $('#hero').draggable({ scroll: false, containment: 'box' });
        //触屏函数
        document.ontouchmove = function (e) {
            var player = $('#hero')[0]
            var touch = e.changedTouches[0];
            let top = touch.pageY - player.offsetHeight / 2;
            let left = touch.pageX - player.offsetWidth / 2;
            player.style.top = `${top}px`;
            player.style.left = `${left}px`;
        };


    </script>



</body>

</html>